<?php
	class FeedAutoDiscovery {
		
		static function getFeedLinks($url=NULL) {
			$feeds = array();
			$html = false;
			if(!isset($url)){
				throw new Exception(__('Url not valid',ARCHIVEPRESS));
			}else{
        		$FeedReader = new FeedReader();
        				
				// I wrote also a "precedure 0" with REGULAR EXPRESSIONS to find the links,
				// but it's very SLOW compared to the others
				// it's much better
				// To use the DOMDocument library to find feed links inside a page
				$xml = new DOMDocument();
				$xml->preserveWhiteSpace = false;
				$xml->formatOutput = false;
				
				// procedure 1: USING DOMDocument but removing content after </html>
				/*
				$html =  file_get_contents($url);
				$html = substr($html,0,(strlen($html)-strpos($html,"</head>")+strlen("</head>")))."</html>";
				@$xml->loadHTML($html); 
				foreach($xml->getElementsByTagName('link') as $link) {
        			if( ( (strtolower($link->getAttribute('rel')) == 'alternate') && ( (strtolower($link->getAttribute('type')) == 'application/rss+xml') || (strtolower($link->getAttribute('type')) == 'application/atom+xml') ) ) || (strtolower($link->getAttribute('type')) == 'application/rss+xml') ){
        				echo $link->getAttribute('href')."<br>";
        			}
				}
				*/
				
				// procedure 2: USING DOMDocument [whole file content]
				// THIS IS THE FASTEST PROCEDURE
				@$xml->loadHTMLFile($url); 
				foreach($xml->getElementsByTagName('link') as $link) {
        			if( ( (strtolower($link->getAttribute('rel')) == 'alternate') && ( (strtolower($link->getAttribute('type')) == 'application/rss+xml') || (strtolower($link->getAttribute('type')) == 'application/atom+xml') ) ) || (strtolower($link->getAttribute('type')) == 'application/rss+xml') ){
        				// check if the link is absolute and if is not 
        				// make it absolute
        				$href = $link->getAttribute('href');
        				$href = url_to_absolute( $url, $href );
        				// verify feed before
        				try {
        					if($FeedReader->isGenuine($href)){
        						array_push($feeds,urldecode($href));
        					}
        				} catch (Exception $e) {
        					// simply don't add it (page not found or similar errors!)
        				}
        			}
				}
				if(count($feeds) > 0) {
					return $feeds;
				}else{
					throw new Exception(__('No feed links found',ARCHIVEPRESS));
				}
			}
		}
	
	}
?>